package com.yunyike.controller.user;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.CartConstants;
import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.RequestConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.controller.BaseController;
import com.yunyike.exception.BadRequestException;
import com.yunyike.model.Recepient;
import com.yunyike.model.User;
import com.yunyike.redis.JedisManager;
import com.yunyike.service.IRecepientService;
import com.yunyike.service.IRegionService;
import com.yunyike.utils.UserUtils;

/**
 * @author zhengqiang.shi
 * 2015年11月26日 下午10:29:51
 */
@Controller
@RequestMapping(value=RequestConstant.USER+RequestConstant.ADDRESS)
public class RecepientController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(RecepientController.class);
	
	@Autowired
	private IRecepientService recepientService;
	
	@Autowired
	private IRegionService regionService;
	
	/**
	 * 根据用户查询地址信息
	 */
	@RequestMapping(value=RequestConstant.ADDRESS_LIST)
	public String findByUser(Model model){
		
		log.info("find recepient by user...");
		
		// 当前用户信息
		User user = getCurrentUser();
		
		// 收货地址信息
		model.addAttribute("recepientList", recepientService.findRecepientByUser(user.getUserId()));
		
		return ResponseConstant.USER_RECEPIENT;
	}
	
	/**
	 * 跳转更新地址页面
	 */
	@RequestMapping(value=RequestConstant.ADDRESS_EDIT+"/{addressId}")
	public String editById(Model model,@PathVariable String addressId){
		
		log.info("edit recepient by id...,addressId:"+addressId);
		
		if(StringUtils.isBlank(addressId) || "0".equals(addressId)){
			log.info("to add recepient page");
			return ResponseConstant.USER_RECEPIENT_EDIT;
		}
		
		// 当前用户信息
		User user = getCurrentUser();
		
		// 收货地址信息
		List<Recepient> list = recepientService.findRecepientByUser(user.getUserId());
		
		// 安全验证
		Recepient recepient = checkRecepient(list,addressId);
		
		model.addAttribute("recepient", recepient);
		
		return ResponseConstant.USER_RECEPIENT_EDIT;
	}
	
	/**
	 * 修改或者添加收货地址
	 */
	@RequestMapping(value=RequestConstant.ADDRESS_UPDATE,method=RequestMethod.POST)
	public String updateAddress(Model model,@Validated Recepient recepient,BindingResult br){
		
		log.info("update recepient by id...,recepient:"+recepient);
		
		//checkRequest(br);
		
		// 当前用户信息
		User user = getCurrentUser();
		
		String recepientId = recepient.getRecepientId();
		
		int result = 0;
		
		// 设置省市区的名称
		recepient.setRecepientProvinceName(regionService.findProvinceName(recepient.getRecepientProvinceId()));
		recepient.setRecepientCityName(regionService.findCityName(recepient.getRecepientCityId()));
		recepient.setRecepientAreaName(regionService.findProvinceName(recepient.getRecepientAreaId()));
		
		// 添加
		if(StringUtils.isBlank(recepientId)){
			log.info("add recepient...");
			recepient.setRecepientId(UUID.randomUUID().toString());
			recepient.setIsDefault(CommonConstant.NUMBER_0);
			recepient.setUserId(user.getUserId());
			recepient.setRecepientStatus(CommonConstant.NUMBER_1);
			result = recepientService.addRecepient(recepient);
		}else{ // 更新
			// 收货地址信息
			List<Recepient> list = recepientService.findRecepientByUser(user.getUserId());
			
			// 安全验证
			Recepient recepientDB = checkRecepient(list,recepientId);
			if(recepientDB == null){
				log.error("update failed.because this recepient is not for current user.recepientId:"+recepientId+"\tuserId:"+user.getUserId());
				throw new BadRequestException();
			}else{
				log.info("update recepient...");
				result = recepientService.updateRecepient(recepient);
			}
		}
		
		log.info("updateAddress end.result:"+result);
		
		return ResponseConstant.REDIRECT+RequestConstant.USER+RequestConstant.ADDRESS+RequestConstant.ADDRESS_LIST;
	}
	
	/**
	 * 删除收货地址
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.ADDRESS_REMOVE+"/{recepientId}")
	public String removeAddress(Model model,@PathVariable String recepientId){
		
		log.info("remove recepient by id...,recepientId:"+recepientId);
		
		if(StringUtils.isBlank(recepientId)){
			log.error("remove recepient request param is not correct.");
			return ResponseConstant.FAILED;
		}
		
		// 当前用户信息
		User user = getCurrentUser();
		
		// 收货地址信息
		List<Recepient> list = recepientService.findRecepientByUser(user.getUserId());
		
		int result = 0;
		
		// 安全验证
		Recepient recepientDB = checkRecepient(list,recepientId);
		if(recepientDB == null){
			log.error("remove failed.because this recepient is not for current user.recepientId:"+recepientId+"\tuserId:"+user.getUserId());
			return ResponseConstant.FAILED;
		}else{
			log.info("remove recepient...");
			recepientDB.setRecepientStatus(CommonConstant.NUMBER_0);
			result = recepientService.updateRecepient(recepientDB);
			
		}
		
		log.info("remove recepient end.result:"+result);
		
		return ResponseConstant.SUCCESS;
	}
	
	/**
	 * 设置默认收货地址
	 * @param addressId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.ADDRESS_SET_DEFAULT+"/{addressId}")
	public String setDefaultAddress(@PathVariable String addressId){
		
		log.info("set default recepient...,addressId:"+addressId);
		
		if(StringUtils.isBlank(addressId) || "0".equals(addressId)){
			log.error("request param not correct");
			return ResponseConstant.FAILED;
		}
		
		// 当前用户信息
		User user = getCurrentUser();
		
		// 收货地址信息
		List<Recepient> list = recepientService.findRecepientByUser(user.getUserId());
		
		// 安全验证
		Recepient recepient = checkRecepient(list,addressId);
		if(recepient == null){
			log.error("this address is not for current user.userId:"+user.getUserId());
			return ResponseConstant.FAILED;
		}
		
		// 设置默认收货地址
		recepient.setIsDefault(CommonConstant.NUMBER_1);
		int result = recepientService.setDefaultRecepient(recepient);
		
		if(result == CommonConstant.NUMBER_1){
			log.info("set default recepient end.");
			return ResponseConstant.SUCCESS;
		}
		
		log.info("set default recepient end.but result isn't 1. set default recepient failed.");
		return ResponseConstant.FAILED;
		
	}
	
	private Recepient checkRecepient(List<Recepient> list, String addressId){
	
		if(list == null || list.isEmpty()){
			log.info("checkRecepient return null,because list was empty.");
			return null;
		}
		
		for (Recepient recepient : list) {
			
			if(recepient.getRecepientId().equals(addressId)){
				log.info("checkRecepient return recepient.");
				return recepient;
			}
		}
		log.info("checkRecepient return null,match failed.");
		return null;
	}
}
